<template>
  <a-modal
    v-model:open="visible"
    :mask-closable="false"
    width="40%"
    title="新增"
    :style="{ top: '20px' }"
    :footer="null"
  >
    <div v-if="visible" v-permission="['xingyun:basedata:add']" v-loading="loading">
      <a-form
        ref="form"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
        :model="formData"
        :rules="rules"
      >
        <a-divider>基本信息</a-divider>
        <a-form-item label="卡券类型" name="couponType">
          <a>{{ $enums.COUPON_TYPE.getDesc(formData.couponType) }}</a>
        </a-form-item>
        <a-form-item label="卡券名称" name="couponName">
          <a-input v-model:value="formData.couponName" max-length="20" allow-clear />
        </a-form-item>
        <a-form-item label="发放方式" name="sendWay">
          <a-select v-model:value="formData.sendWay" allow-clear>
            <a-select-option
              v-for="item in $enums.SEND_WAY.values()"
              :key="item.code"
              :value="item.code"
              >{{ item.desc }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item label="售价" name="price">
          <a-input-number
            addon-after="￥"
            precision="2"
            min="0.00"
            style="width: 100%"
            v-model:value="formData.price"
          />
        </a-form-item>
        <a-form-item label="卡券面值" name="parValue">
          <a-input-number
            addon-after="￥"
            precision="2"
            min="0.00"
            style="width: 100%"
            v-model:value="formData.parValue"
          />
        </a-form-item>
        <a-form-item label="增值" name="added" v-if="formData.couponType === 2">
          <a-input-group compact>
            <a-input-number
              addon-after="%"
              precision="2"
              min="0.00"
              max="100.00"
              style="width: 30%"
              v-model:value="formData.added"
            />
            <a-input-number
              addon-after="￥"
              precision="2"
              min="0.00"
              max="100.00"
              style="width: 70%"
              :value="(formData.added / 100) * formData.parValue"
              readonly
            />
          </a-input-group>
        </a-form-item>
        <a-form-item label="有效期" name="effectiveDay">
          <a-input-number
            addon-after="天"
            min="0.00"
            style="width: 100%"
            v-model:value="formData.effectiveDay"
          />
        </a-form-item>
        <a-form-item label="备注" name="description">
          <a-textarea v-model:value="formData.description" max-length="200" />
        </a-form-item>
        <a-divider>适用配置</a-divider>
        <a-form-item label="使用条件" name="useCondition">
          <a-input-number
            addon-after="￥"
            precision="2"
            min="0.00"
            max="100.00"
            style="width: 100%"
            v-model:value="formData.useCondition"
          />
        </a-form-item>
        <a-form-item label="适用门店" name="stopAll">
          <a-row>
            <a-col :span="24">
              <div style="padding-top: 5px">
                <a-radio-group v-model:value="formData.stopAll" name="stopAllGroup">
                  <a-radio :value="true">全部门店</a-radio>
                  <a-radio :value="false">指定门店</a-radio>
                </a-radio-group>
              </div>
            </a-col>
          </a-row>
          <a-row v-if="!formData.stopAll">
            <a-col :span="24">
              <div style="padding-top: 5px">
                <shop-selector v-model:value="formData.shopIds" :multiple="true" :show-sum="true" />
              </div>
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item label="适用商品" name="productAll">
          <a-row>
            <a-col :span="24">
              <div style="padding-top: 5px">
                <a-radio-group v-model:value="formData.productAll" name="productAllGroup">
                  <a-radio :value="true">全部商品</a-radio>
                  <a-radio :value="false">指定商品</a-radio>
                </a-radio-group>
              </div>
            </a-col>
          </a-row>
          <a-row v-if="!formData.productAll">
            <a-col :span="24">
              <product-edit v-model:tableData="formData.products" />
            </a-col>
          </a-row>
        </a-form-item>
        <div class="form-modal-footer">
          <a-space>
            <a-button type="primary" :loading="loading" html-type="submit" @click="submit"
              >保存</a-button
            >
            <a-button :loading="loading" @click="closeDialog">取消</a-button>
          </a-space>
        </div>
      </a-form>
    </div>
  </a-modal>
</template>
<script>
  import { defineComponent } from 'vue';
  import * as api from '@/api/base-data/coupon';
  import ProductEdit from '@/views/base-data/product/productEdit.vue';
  import ShopSelector from '@/components/Selector/src/ShopSelector.vue';

  export default defineComponent({
    components: { ShopSelector, ProductEdit },
    data() {
      return {
        // 是否可见
        visible: false,
        // 是否显示加载框
        loading: false,
        // 表单数据
        formData: {},
        // 表单校验规则
        rules: {
          couponType: [{ required: true, message: '请输入卡券类型' }],
          couponName: [{ required: true, message: '请输入卡券名称' }],
          sendWay: [{ required: true, message: '请输入发放方式' }],
          effectiveDay: [{ required: true, message: '请输入有效天数' }],
          available: [{ required: true, message: '请输入状态' }],
          description: [{ required: true, message: '请输入备注' }],
          parValue: [{ required: true, message: '请输入面值' }],
          added: [{ required: true, message: '请输入增值比例' }],
          useCondition: [{ required: true, message: '请输入使用条件' }],
          price: [{ required: true, message: '请输入售价' }],
          productAll: [
            { required: true, message: '请输入适用商品' },
            {
              validator: (rule, value, callback) => {
                if (!this.formData.productAll && !this.formData.products?.length) {
                  callback(new Error('请输入适用商品'));
                } else {
                  callback();
                }
              },
            },
          ],
          stopAll: [
            { required: true, message: '请输入适用门店' },
            {
              validator: (rule, value, callback) => {
                if (!this.formData.stopAll && !this.formData.shopIds?.length) {
                  callback(new Error('请输入适用门店'));
                } else {
                  callback();
                }
              },
            },
          ],
        },
      };
    },
    computed: {},
    watch: {
      'formData.couponType': {
        handler(newVal) {
          if (newVal !== 2) {
            this.formData.added = 0;
          }
        },
      },
      'formData.stopAll': {
        handler(newVal) {
          if (newVal) {
            this.formData.shops = [];
          }
        },
      },
      'formData.productAll': {
        handler(newVal) {
          if (newVal) {
            this.formData.products = [];
          }
        },
      },
    },
    created() {
      // 初始化表单数据
      this.initFormData();
    },
    methods: {
      // 打开对话框 由父页面触发
      openDialog() {
        this.visible = true;

        this.$nextTick(() => this.open());
      },
      // 关闭对话框
      closeDialog() {
        this.visible = false;
        this.$emit('close');
      },
      // 初始化表单数据
      initFormData() {
        this.formData = {
          couponType: 1,
          couponName: '',
          sendWay: 1,
          effectiveDay: 30,
          available: true,
          description: '',
          parValue: null,
          added: 0,
          useCondition: 0,
          price: '',
          stopAll: true,
          shopIds: [],
          productAll: true,
          productIds: [],
          products: [],
        };
      },
      // 提交表单事件
      submit() {
        this.$refs.form.validate().then((valid) => {
          if (valid) {
            this.loading = true;
            api
              .create({
                ...this.formData,
                productIds: (this.formData.products?.map((item) => item.productId) || []).join(','),
                products: null,
                shopIds: (this.formData.shopIds || []).join(','),
              })
              .then(() => {
                this.$msg.createSuccess('新增成功！');
                this.$emit('confirm');
                this.visible = false;
              })
              .finally(() => {
                this.loading = false;
              });
          }
        });
      },
      // 页面显示时触发
      open() {
        // 初始化表单数据
        this.initFormData();
      },
    },
  });
</script>
